package com.ibuonline.b2b.common;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.dimeng.common.util.StringUtil;

public class AtagFilter {
	
	public static String replaceAtag(String html) {
		if (StringUtil.isEmpty(html)) return html;
		Matcher matcher = Pattern.compile("<[aA][^>]*>").matcher(html);
    	List<String[]> list = new ArrayList<String[]>();
    	while (matcher.find()) {
    		String atag = matcher.group().toLowerCase();
    		if (atag.indexOf("taojindi.com") > -1){
    			continue;
    		}
    		String href ="";
    		String newAtag = atag;
    		int pos1 = atag.indexOf("href=\"");
    		if (pos1 > 0) {
    			int pos2 = atag.indexOf('"', pos1+6);
        		if (pos2 > 0) {
        			href = atag.substring(pos1+6, pos2);
        			if (href.equals("#") || href.startsWith("javascript") || href.equals("") || href.startsWith("mailto:"))
        				continue;
    				try {
						String newhref = "http://www.taojindi.com/goto?url=" + java.net.URLEncoder.encode(href,"GBK");
						newAtag = newAtag.replace(href, newhref);
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
					
        		}
        		if (atag.indexOf("tagert=\"") <0){
        			newAtag = newAtag.replace(">", " target=\"_blank\" >");
        		}
        		list.add(new String[]{atag,newAtag});
    		}
    	}
		for (String[] str:list){
			html = html.replace(str[0], str[1]);
		}
		return html;
	}
	public static void main(String[] strs) {
		String a = "<a href=\"www.qq.com\" alt=\"sd\">";
		System.out.println(replaceAtag(a));
	}
	
	
	
}
